<template>
  <div style="margin-top: 2vh">
    <div style="background-color: white; width: 68vw; margin: auto;">
      <!-- 上方标题 -->
      <div style="border-bottom: 1px solid #e9e9e9; height: 7vh; width: 100%;">
        <span style="font-weight: bold; font-size: 1.1rem; line-height: 7vh; margin-left: 1.5vw;">论文上传</span>
        <span style="font-size: 0.8rem; color: #8c8c8c; margin-left: 1vw; line-height: 7vh;">请上传您发表的论文的</span>
        <span style="color: #8c8c8c; line-height: 7vh; font-size: 0.8rem; font-weight: bold;">重要信息: 封面 / 目录 / 文章 / 封底, 检索报告等。</span>
      </div>

      <pdf-preview
          ref="pdfPreviewRef"
          @update:pdf-path="updatePdfPath"
          @rotations-changed="handleRotationsChanged"
      ></pdf-preview>
    </div>

    <!-- 填写信息 -->
    <div style="background-color: white; width: 68vw; margin: auto; display: flex; flex-direction: column;padding-bottom: 5vh;margin-top: 3vh;margin-bottom: 3vh ">
      <div style="flex: 1;">
        <div style="border-bottom: 1px solid #e9e9e9;height: 7vh;display: flex;">
          <span style="font-weight: bold;font-size: 1.1rem;line-height: 7vh;margin-left: 1.5vw">填写信息</span>
          <smart-paper-form style="line-height: 7vh;margin-left: 3vh" @update:form="updateFormData"></smart-paper-form>
          <span style="line-height: 7vh; margin-left: 3vh;color: #CACACA;font-weight: bold">带<span style="color: red;"> * </span>号为必填项</span>
        </div>
        <div>
          <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px" style="margin-top: 5vh">
            <el-form-item label="论文标题" prop="title" required>
              <el-input v-model="ruleForm.title" placeholder="请填写标题" style="width: 34vw;"></el-input>
            </el-form-item>
            <el-form-item label="论文类型" prop="paperType" required>
              <el-radio-group v-model="ruleForm.paperType">
                <el-radio label="期刊论文"></el-radio>
                <el-radio label="会议论文集"></el-radio>
                <el-radio label="报纸"></el-radio>
                <el-radio label="学位论文"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="论文领域" prop="researchField">
              <el-radio-group v-model="ruleForm.researchField">
                <el-radio label="科研(社科)"></el-radio>
                <el-radio label="科研(自科)"></el-radio>
                <el-radio label="教育"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="本人排名" prop="authorRank" required>
              <el-select v-model="ruleForm.authorRank" style="width: 34vw;">
                <el-option label="无" :value="0"></el-option>
                <el-option v-for="i in 13" :key="i" :label="i.toString()" :value="i"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="通讯作者" prop="correspondingAuthor">
              <el-radio-group v-model="ruleForm.correspondingAuthor">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="刊物名称" prop="journalName" required>
              <el-input v-model="ruleForm.journalName" placeholder="如: 装饰" style="width: 34vw;"></el-input>
            </el-form-item>
            <el-form-item label="收录检索" prop="indexing">
              <el-checkbox-group v-model="ruleForm.indexing">
                <el-checkbox label="SCI"></el-checkbox>
                <el-checkbox label="SCIE"></el-checkbox>
                <el-checkbox label="SSCI"></el-checkbox>
                <el-checkbox label="ESCI"></el-checkbox>
                <el-checkbox label="自然指数杂志"></el-checkbox>
                <el-checkbox label="CSSCI"></el-checkbox>
                <el-checkbox label="CSSCI扩展版"></el-checkbox>
                <el-checkbox label="CSCD-C"></el-checkbox>
                <el-checkbox label="CSCD-E"></el-checkbox>
                <el-checkbox label="SCD"></el-checkbox>
                <el-checkbox label="AHCI"></el-checkbox>
                <el-checkbox label="EI"></el-checkbox>
                <el-checkbox label="CPCI-S (ISTP)"></el-checkbox>
                <el-checkbox label="CPCI-SSH (ISSHP)"></el-checkbox>
                <el-checkbox label="PKU (中文核心)"></el-checkbox>
                <el-checkbox label="科技核心"></el-checkbox>
                <el-checkbox label="国家级期刊"></el-checkbox>
                <el-checkbox label="省级期刊"></el-checkbox>
                <el-checkbox label="校内核心"></el-checkbox>
                <el-checkbox label="会议论文"></el-checkbox>
                <el-checkbox label="其他"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="发表时间" prop="publishDate" required>
              <el-date-picker
                  v-model="publishDateModel"
                  type="date"
                  placeholder="选择日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="DOI号" prop="doi">
              <el-input v-model="ruleForm.doi" placeholder="请输入DOI号" style="width: 34vw;"></el-input>
            </el-form-item>
            <el-form-item label="引用次数" prop="citationCount">
              <el-input v-model="ruleForm.citationCount" placeholder="请输入论文引用次数" style="width: 34vw;"></el-input>
            </el-form-item>
            <el-form-item label="关键词" prop="keywords">
              <el-input v-model="ruleForm.keywords" placeholder="如: 机器学习,生物化学" style="width: 34vw;"></el-input>
            </el-form-item>
            <el-form-item label="起止页码" prop="pageRange" required>
              <el-input v-model="ruleForm.pageRange" placeholder="如: 21~24" style="width: 34vw;"></el-input>
            </el-form-item>
            <el-form-item label="是否同步" prop="syncStatus" required>
              <el-select v-model="ruleForm.syncStatus" style="width: 34vw;" placeholder="请选择是否同步">
                <el-option label="是" :value="'是'"></el-option>
                <el-option label="否" :value="'否'"></el-option>
              </el-select>
            </el-form-item>


            <el-form-item label="关联课题" prop="projectId">
              <el-select v-model="ruleForm.projectId" placeholder="请选择本成果所属课题,以便使用结题助手功能" style="width: 34vw;">
                <el-option
                    v-for="project in longitudinalProjects"
                    :key="project.id"
                    :label="project.projectName"
                    :value="project.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="作者信息" prop="authorInfo">
              <div style="background-color: #f9f9f9; width: 55vw; height: auto; padding: 10px; border-radius: 4px;">
                <!-- 表头 -->
                <div style="display: flex; align-items: center; padding: 8px 0; border-bottom: 1px solid #e8e8e8;">
                  <div style="width: 60px; text-align: center;">排序</div>
                  <div style="width: 100px; margin-left: 10px;">姓名</div>
                  <div style="width: 120px; margin-left: 10px;">作者身份</div>
                  <div style="width: 80px; margin-left: 10px; text-align: center;">通讯作者</div>
                  <div style="width: 80px; margin-left: 10px; text-align: center;">共同一作</div>
                  <div style="flex: 1; margin-left: 10px;">单位名称</div>
                  <div style="width: 80px; margin-left: 10px;">操作</div>
                </div>

                <!-- 作者列表 -->
                <div v-for="(author, index) in ruleForm.authorInfo" :key="index"
                     style="display: flex; align-items: center; padding: 8px 0; border-bottom: 1px solid #f0f0f0;">
                  <el-select v-model="author.rank" style="width: 60px;">
                    <el-option
                        v-for="item in rankOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                  </el-select>

                  <el-input v-model="author.name" style="width: 100px; margin-left: 10px;"></el-input>

                  <el-select v-model="author.identity" style="width: 120px; margin-left: 10px;">
                    <el-option
                        v-for="item in shipOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                  </el-select>

                  <div style="width: 80px; margin-left: 10px; display: flex; justify-content: center;">
                    <el-checkbox v-model="author.isCorresponding"></el-checkbox>
                  </div>

                  <div style="width: 80px; margin-left: 10px; display: flex; justify-content: center;">
                    <el-checkbox v-model="author.isCoFirstAuthor"></el-checkbox>
                  </div>

                  <el-select v-model="author.institution" placeholder="单位名称" style="flex: 1; margin-left: 10px;">
                    <el-option label="信息工程学院" value="信息工程学院"></el-option>
                  </el-select>


                  <el-button
                      type="danger"
                      size="small"
                      @click="removeAuthor(index)"
                      style="width: 80px; margin-left: 10px;">
                    删除
                  </el-button>
                </div>

                <el-button @click="addAuthor" style="margin-top: 10px;">添加共同作者</el-button>
              </div>
            </el-form-item>
            <el-form-item label="影响因子" prop="impactFactor">
              <el-input v-model="ruleForm.impactFactor" placeholder="如: 3.102" style="width: 34vw;"></el-input>
            </el-form-item>
            <el-form-item label="卷号" prop="volumeNumber">
              <el-input v-model="ruleForm.volumeNumber" placeholder="如: 36" style="width: 34vw;"></el-input>
            </el-form-item>
            <el-form-item label="期号" prop="issueNumber">
              <el-input v-model="ruleForm.issueNumber" placeholder="如: 12" style="width: 34vw;"></el-input>
            </el-form-item>
            <el-form-item label="ISSN号" prop="issn">
              <el-input v-model="ruleForm.issn" placeholder="请输入ISSN号" style="width: 34vw;"></el-input>
            </el-form-item>
            <el-form-item label="CN号" prop="cnNumber">
              <el-input v-model="ruleForm.cnNumber" placeholder="请输入CN号" style="width: 34vw;"></el-input>
            </el-form-item>
            <el-form-item label="摘要" prop="abstractContent">
              <el-input type="textarea" :rows="4" v-model="ruleForm.abstractContent" placeholder="请输入摘要" style="width: 34vw;"></el-input>
            </el-form-item>
            <el-form-item label="备注信息" prop="remarks">
              <el-input type="textarea" :rows="4" v-model="ruleForm.remarks" placeholder="请输入备注信息" style="width: 34vw;"></el-input>
            </el-form-item>
          </el-form>
          <div style="display: flex;justify-content: center;margin-top: 2vh">
            <button @click="submit" class="upload-button" style="width: 10vw;" :disabled="isSubmitting">
              {{ isSubmitting ? '上传中...' : '上 传' }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, computed, watch, onMounted} from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import PdfPreview from "@/components/PdfPreview.vue"
import { savePaper } from "@/api/Manage/paper.js"
import SmartPaperForm from "@/components/smart/smart-paper-form.vue";
import {getCompletedLongitudinal} from "@/api/Research/Longitudinal.js";
import { batchUpdatePdfPages } from "@/api/Manage/File.js";

const longitudinalProjects = ref([])
const router = useRouter()
const ruleFormRef = ref(null)
const pdfPreviewRef = ref(null)
const isSubmitting = ref(false) // 提交状态
const hasRotations = ref(false) // 是否有旋转
const currentRotations = ref([]) // 存储当前的旋转信息

const ruleForm = reactive({
  title: '',
  pdfPath: '',
  paperType: '',
  researchField: '',
  authorRank: 0,
  correspondingAuthor: false,
  journalName: '',
  indexing: [],
  publishDate: '',
  doi: '',
  syncStatus: "是",
  citationCount: null,
  keywords: '',
  pageRange: '',
  projectId: null,
  impactFactor: null,
  volumeNumber: null,
  issueNumber: null,
  issn: '',
  cnNumber: '',
  abstractContent: '',
  remarks: '',
  authorInfo: [{
    rank: '',
    name: '',
    identity: '',
    isCorresponding: false,
    isCoFirstAuthor: false,
    institution: ''
  }]
})

const publishDateModel = computed({
  get: () => ruleForm.publishDate,
  set: (value) => {
    ruleForm.publishDate = value
  }
})

const rankOptions = [
  { value: '1', label: '1' },
  { value: '2', label: '2' },
  { value: '3', label: '3' },
  { value: '4', label: '4' },
  { value: '5', label: '5' },
  { value: '6', label: '6' },
  { value: '7', label: '7' },
  { value: '8', label: '8' },
  { value: '9', label: '9' },
  { value: '10', label: '10' },
  { value: '11', label: '11' },
  { value: '12', label: '12' },
  { value: '13', label: '13' },
]

const shipOptions = [
  { value: '老师', label: '老师' },
  { value: '博士生', label: '博士生' },
  { value: '硕士生', label: '硕士生' },
  { value: '本科生', label: '本科生' },
  { value: '其他', label: '其他' }
]

const rules = {
  title: [
    { required: true, message: '请输入论文标题', trigger: 'blur' }
  ],
  paperType: [
    { required: true, message: '请选择论文类型', trigger: 'change' }
  ],
  // 新增：起始页码必填规则
  pageRange: [
    { required: true, message: '请输入起止页码', trigger: 'blur' }
  ],
  // 新增：作者信息必填规则
  authorInfo: [
    {
      required: true,
      message: '请至少填写一位作者信息',
      trigger: 'change',
      validator: (rule, value, callback) => {
        // 验证至少有一位作者，且姓名不为空
        if (value.length === 0) {
          callback(new Error('请添加作者信息'));
        } else if (!value[0].name) {
          callback(new Error('第一位作者姓名不能为空'));
        } else {
          callback();
        }
      }
    }
  ]
  // Add other rules as needed
}

const addAuthor = () => {
  ruleForm.authorInfo.push({
    rank: '',
    name: '',
    identity: '',
    isCorresponding: false,
    isCoFirstAuthor: false,
    institution: ''
  })
}

const removeAuthor = (index) => {
  ruleForm.authorInfo.splice(index, 1)
}

const updatePdfPath = (pdfPath) => {
  ruleForm.pdfPath = pdfPath.firstImageUrl
}

// 处理旋转状态变化
const handleRotationsChanged = (rotations) => {
  hasRotations.value = rotations.length > 0
  currentRotations.value = rotations
  console.log('旋转状态变化:', rotations)
}

const updateFormData = (formData) => {
  Object.assign(ruleForm, formData)
}

const submit = async () => {
  try {
    isSubmitting.value = true

    // 验证表单
    const valid = await new Promise((resolve) => {
      if (ruleFormRef.value) {
        ruleFormRef.value.validate((valid) => resolve(valid))
      } else {
        resolve(true)
      }
    })
    if (!valid) {
      ElMessage.error('请填写必填项')
      return
    }

    // 如果有旋转，先保存旋转
    if (hasRotations.value && currentRotations.value.length > 0 && ruleForm.pdfPath) {
      try {
        // 组装批量更新请求数据
        const batchData = {
          filePath: ruleForm.pdfPath, // PDF文件路径
          pages: currentRotations.value.map(rotation => ({
            pageNumber: rotation.pageIndex + 1, // 页码从1开始
            rotation: rotation.rotation // 旋转角度
          }))
        }

        console.log('批量更新旋转请求数据:', batchData)

        const rotationResult = await batchUpdatePdfPages(batchData)
        console.log('批量更新旋转结果:', rotationResult)

        if (rotationResult.code !== "0") {
          ElMessage.error('保存旋转失败: ' + (rotationResult.message || '未知错误'))
          return
        }

        ElMessage.success('旋转保存成功')

        // 重置旋转状态
        hasRotations.value = false
        currentRotations.value = []

        // 通知PDF预览组件重新加载
        if (pdfPreviewRef.value && pdfPreviewRef.value.reloadPDF) {
          await pdfPreviewRef.value.reloadPDF(ruleForm.pdfPath)
        }

      } catch (rotationError) {
        console.error('保存旋转失败:', rotationError)
        ElMessage.error('保存旋转失败: ' + (rotationError.message || '网络错误'))
        return
      }
    }

    console.log("ruleForm", ruleForm)
    const result = await savePaper(ruleForm)

    if (result.code === 1) {
      ElMessage.success('论文上传成功')
      router.push('/main/result/papers')
    } else {
      ElMessage.error('上传失败，请稍后重试')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败，请稍后重试')
  } finally {
    isSubmitting.value = false
  }
}

// 新增：在组件挂载时调用 getCompletedLongitudinal
onMounted(async () => {
  try {
    const response = await getCompletedLongitudinal();
    if (response.code === 1 && Array.isArray(response.data)) {
      longitudinalProjects.value = response.data;
    } else {
      ElMessage.error('获取结题的纵向课题失败');
    }
  } catch (error) {
    console.error('获取结题的纵向课题出错:', error);
    ElMessage.error('获取结题的纵向课题失败，请刷新页面重试');
  }
});


</script>

<style scoped>
.upload-button {
  height: 5vh;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 1rem;
  cursor: pointer;
}

.upload-button:hover:not(:disabled) {
  background-color: #45a049;
}

.upload-button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}
</style>
